package com.ycl.blog.config;

import com.ycl.blog.base.identity.IdentityUser;
import com.ycl.blog.bean.po.JwtUserPo;
import com.ycl.blog.enums.ApplicationEnum;
import com.ycl.blog.exception.AppException;
import com.ycl.blog.util.CopyUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by Administrator on 2017/12/12.
 */
@Slf4j
public class JwtUserUtil {

    public static JwtUserPo getJwtUser(String authorization) throws AppException {

        JwtUserPo jwtUser;

        Claims claims = getClaims(authorization);
        if (claims == null) {
            return null;
        }

        String userAccount = claims.getSubject();
        if (StringUtils.isEmpty(userAccount)) {
            throw new AppException("会话里的用户账号为空");
        }

        String userId = (String) claims.get("userId");
        if (StringUtils.isEmpty(userId)) {
            throw new AppException("会话里的用户id为空");
        }

        jwtUser = new JwtUserPo();
        jwtUser.setUserId(userId);
        jwtUser.setUserAccount(userAccount);

        return jwtUser;
    }

    public static String createToken(String userAccount, String userId) throws AppException {
        Date expDate = new Date(System.currentTimeMillis() + Constants.ExpTime.UserExpTime * 1000);

        String token = Jwts.builder().setSubject(userAccount).setExpiration(expDate).claim("userId", userId)
                .signWith(SignatureAlgorithm.HS256, Constants.JWT_SECRET).compact();

//        redisComponent.put(token, new Date(), Constants.ExpTime.CUserExpTime);

        return token;
    }

    public static IdentityUser decryptToken(String authorization) throws AppException {

        JwtUserPo jwtUserPo = getJwtUser(authorization);
        IdentityUser identityUser = CopyUtil.transfer(jwtUserPo, IdentityUser.class);

        return identityUser;
    }


    /**
     * 获取会话
     *
     * @param token
     * @return
     * @throws AppException
     */
    public static Claims getClaims(String token) throws AppException {

        // 没有登陆信息
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        //JWT token验证
        Claims claims = Jwts.parser().setSigningKey(Constants.JWT_SECRET)
                .parseClaimsJws(token).getBody();

        if (claims.getExpiration().before(new Date())) {
            throw new AppException(ApplicationEnum.TOKEN_INVALID);
        }

        /*if (redisComponent.get(token, Date.class) == null) {
            throw new JwtUserException(202, "当前请求已过期，请重新登陆");
        }*/

        return claims;
    }

    /**
     * 清除会话
     *
     * @param request
     * @throws AppException
     */
    public static void evictToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authHeader)) {
            authHeader = request.getParameter("Authorization");
        }

        // 没有登陆信息
        if (StringUtils.isEmpty(authHeader)) {
            return;
        }
//        redisComponent.evict(authHeader);
    }

    public static void main(String[] args) {
        String userCode = "111111";
        Date expDate = new Date(System.currentTimeMillis() + Constants.ExpTime.UserExpTime * 1000);

        String token = Jwts.builder().setSubject(userCode).setExpiration(expDate)
                .signWith(SignatureAlgorithm.HS256, Constants.JWT_SECRET).compact();
        System.out.println(token);
    }
}
